package cate.game.server.rpc.dispatch;

import cp.solution.rpc.RpcMsgHead;
import cp.solution.rpc.listener.RpcFireAndForgetListener;
import cp.solution.rpc.listener.RpcFireAndForgetListenerPack;
import easy.java.practice.errorcode.EcException;

import java.util.*;

public class RpcFafDispatcher {

    protected Map<String, List<RpcFireAndForgetListenerPack>> map = new HashMap<>();

    public void addListener(String path, RpcFireAndForgetListener handler, int priority) {
        List<RpcFireAndForgetListenerPack> packs = map.get(path);
        if (packs == null) {
            packs = new ArrayList<>();
            packs.add(new RpcFireAndForgetListenerPack(handler, priority));
            map.put(path, packs);
        } else {
            Iterator<RpcFireAndForgetListenerPack> pIter = packs.iterator();
            while (pIter.hasNext()) {
                RpcFireAndForgetListenerPack thePack = pIter.next();
                if (thePack.handler.hashCode() == handler.hashCode()) {
                    pIter.remove();
                }
            }
            packs.add(new RpcFireAndForgetListenerPack(handler, priority));
        }
    }

    public void dispatch(RpcMsgHead head, byte[] msgBody) {
        List<RpcFireAndForgetListenerPack> packs = map.get(head.path());
        if(packs == null || packs.isEmpty()) {
            throw new EcException("缺少path="+head.path()+"的FireAndForget处理器");
        }
        for(RpcFireAndForgetListenerPack pack : packs) {
            pack.handler.accept(head, msgBody);
        }
    }

}
